<template>
  <!-- 面包屑 -->
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item><b>签到</b></el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <!-- 数据表格 -->
  <div style="margin:40px 20px 20px 20px">
    <el-table :data="tableCourse" stripe border style="width: 100%">
      <el-table-column prop="cname" label="课程名" align="center"/>
      <el-table-column prop="tname" label="任课教师" align="center"/>
      <el-table-column prop="signtime" label="发起时间" align="center"/>
      <el-table-column prop="reacttime" label="签到时间" align="center"/>
      <el-table-column label="操作" align="center" width="150">
        <template #default="scope">
          <el-button
              v-if="canSign(scope.row)"
              type="primary"
              @click="sign(scope.row)"
          >
            签到
          </el-button>
          <el-button
              v-else-if="scope.row.reacttime"
              type="info"
              disabled
          >
            已签到
          </el-button>
          <el-button
              v-else-if="scope.row.isTimeout"
              type="warning"
              disabled
          >
            超时
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!-- 分页 -->
  <div class="pagination-container">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5,10]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="sizes, prev, pager, next"
        :total="totals"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue';
import request from "@/utils/class";
import { ElMessage, ElButton } from 'element-plus';
import { useRouter } from 'vue-router';

const tableCourse = ref([]);
const totals = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);

onMounted(() => {
  getCourse();
});

const getCourse = () => {
  // 模拟从 sessionStorage 获取 sid
  const loginUser = sessionStorage.getItem('loginUser');
  const user = JSON.parse(loginUser);
  const sid = user.sid;

  const params = {
    sid: sid,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  };

  request({
    url: '/sign/all',
    method: 'get',
    params,
  }).then(response => {
    if (response.data.errorCode == 200) {
      const records = response.data.data.records.map(record => {
        const signTime = formatDate(new Date(record.signtime));
        const hasReacted = !!record.reacttime;
        const isTimeout = hasReacted ? false : checkTimeout(new Date(record.signtime));
        const row = {
          ...record,
          signtime: signTime,
          reacttime: hasReacted ? formatDate(new Date(record.reacttime)) : null,
          isTimeout: isTimeout
        };
        return row;
      });
      tableCourse.value = records;
      totals.value = response.data.data.total;
    }
  });
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getCourse();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getCourse();
};

const sign = (row) => {
  if (!row.isTimeout) {
    request({
      url: '/sign/success',
      method: 'put',
      data: { id: row.id }
    }).then(() => {
      ElMessage.success('签到成功！');
      row.reacttime = new Date();
      row.isTimeout = false;
      getCourse(); // 重新获取课程列表以刷新界面
    }).catch(error => {
      console.error("请求失败:", error);
      ElMessage.error("签到失败");
    });
  } else {
    ElMessage.warning('您已超时，无法签到！');
  }
};

const canSign = (row) => {
  return !row.reacttime && !row.isTimeout;
};

const checkTimeout = (signTime) => {
  const currentTime = new Date();
  const elapsedTime = (currentTime - signTime) / 1000 / 60; // 转换为分钟
  return elapsedTime > 5;
};

// 用于定时检查超时的函数
const setTimeoutCheck = (row) => {
  if (!row.reacttime) {
    const intervalId = setInterval(() => {
      if (checkTimeout(row.signtime)) {
        row.isTimeout = true;
        clearInterval(intervalId); // 超时后清除定时器
      }
    }, 60000); // 每分钟检查一次
  }
};

// 组件挂载时获取课程列表，并为每条记录设置定时器
onMounted(() => {
  getCourse();
  tableCourse.value.forEach(row => {
    if (!row.reacttime) {
      setTimeoutCheck(row);
    }
  });
});
</script>

<style scoped>
/* 分页居中样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px auto;
}

/* 面包屑样式 */
.el-breadcrumb {
  font-size: 18px;
  margin-top: 20px;
  margin-bottom: 50px;
  margin-left: 20px;
}

.el-table {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  color: #333;
  border-top: 1px solid #e8e8e8;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table th,
.el-table td {
  padding: 10px;
  border-bottom: 1px solid #e8e8e8;
}

.el-table th {
  text-align: center;
  background-color: #eef1f6;
  font-weight: bold;
}
</style>